package com.cris.controller;

import com.cris.service.StuffService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by owen on 2017/5/17.
 */
@Controller
public class LoginController {
    @Autowired
    StuffService stuffService;

    @RequestMapping("/login")
    public String login(HttpServletRequest req) throws Exception {
        //如果登录失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
        //根据shiro返回的异常类路径判断，抛出指定异常信息
        String errorClassName = (String)req.getAttribute("shiroLoginFailure");
        if(UnknownAccountException.class.getName().equals(errorClassName)) {
            req.setAttribute("error", "用户名/密码错误");
        } else if(IncorrectCredentialsException.class.getName().equals(errorClassName)) {
            req.setAttribute("error", "用户名/密码错误");
        } else if(errorClassName != null) {
            req.setAttribute("error", "未知错误：" + errorClassName);
        }
        return "login";
    }
    //注册
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){
        return "register";
    }
    @RequiresPermissions("register")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String doRegister(@RequestParam String name, @RequestParam String password, @RequestParam String role, Model model){
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("role",role);
        map.put("password",password);
        stuffService.addStuff(map);
        return "success";
    }
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout0(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

}
